package com.wiken.ossservice.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.R;
import com.wiken.servicecommon.common.exception.DefaultException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ossservice/upload")
public class uploadFile {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.AccessKeyID}")
    private String accessKeyId;
    @Value("${aliyun.oss.AccessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private final String  DIR = "images/";
    @PostMapping("uploadfile")
    public R uploadfile(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();

        String[] split = filename.split("\\.");
        String suffix = split[split.length - 1];
        filename = new Date().getTime() + "." + suffix;

        System.out.println("filename: " + filename);

        String objectName = DIR + filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String url = "";
        try {
//            InputStream inputStream = new FileInputStream(filePath);
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getUri());
            System.out.println(result.getResponse().getStatusCode());

            url = result.getResponse().getUri();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());

            throw new DefaultException(Code.ERROR_UPLOAD_FILE, "文件上传失败");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            throw new DefaultException(Code.ERROR_UPLOAD_FILE, "文件上传失败");
        } catch (Exception e) {
            throw new DefaultException(Code.ERROR_UPLOAD_FILE, "文件上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        Map<String, String> data = new HashMap<>();
        data.put("url", url );
        return R.ok().message("文件上传成功").code(200).data(data);
    }


}
